package com.tbs.easyhomemoneyserver.handler;


import com.alibaba.fastjson2.JSON;
import com.tbs.easyhomemoneyserver.config.filters.LoginFiltter;
import com.tbs.easyhomemoneyserver.exception.WarnException;
import com.tbs.easyhomemoneyserver.model.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;


@Slf4j //日志注解 可以用log
@RestControllerAdvice
/**
 * 全局异常捕获
 */
public class ExceptionHandler {

    @Resource
    HttpServletRequest request;

    @Resource
    HttpServletResponse response;


    /**
     * 捕获全部异常
     *
     * @param throwable
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler
    public ResultVO errorHandle(Throwable throwable) {
        log.error(throwable.getMessage(), throwable);//Slf4j的效果
        return ResultVO.error(throwable);
    }

    /**
     * 捕获警告异常
     *
     * @param throwable
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(WarnException.class)
    public ResultVO warnHandle(WarnException throwable) {
        log.warn(throwable.getMessage(), throwable);
        return ResultVO.make(throwable, throwable.getMessage(), ResultVO.WARN);
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    public void valid(MethodArgumentNotValidException throwable) throws ServletException, IOException {
        StringBuilder stringBuilder = new StringBuilder();
        int i = 1;
        for (ObjectError error : throwable.getBindingResult().getAllErrors()) {
            stringBuilder.append(String.format("%d.%s \n", i++, error.getDefaultMessage()));
        }
        LoginFiltter.throwError(new RuntimeException(stringBuilder.toString()), request, response);
//        return ResultVO.make(throwable, throwable.getMessage(), ResultVO.ERROR);
    }
}
